package com.hjj.formatter;

import com.hjj.exception.MyDateFormatterException;
import org.springframework.format.Formatter;

import java.text.ParseException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Locale;

public class MyDateFormatter implements Formatter<LocalDate> {
    private String datePatter;
    private String errorMsg;

    public MyDateFormatter(String datePatter, String errorMsg) {
        this.datePatter = datePatter;
        this.errorMsg = errorMsg;
    }

    @Override
    public LocalDate parse(String text, Locale locale) throws ParseException {
        LocalDate parse = null;
        try {
            parse = LocalDate.parse(text, DateTimeFormatter.ofPattern(datePatter));
        } catch (DateTimeParseException e) {
            throw new MyDateFormatterException(errorMsg);
        }
        return parse;
    }

    @Override
    public String print(LocalDate object, Locale locale) {
        return object.format(DateTimeFormatter.ofPattern(datePatter));
    }
}
